import React, { useState } from 'react';
import { View, Text, TextInput, Button, Image, StyleSheet, Alert, ImageBackground } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import ImageConstants from '../resources/ImageConstants';
import { useDispatch } from 'react-redux';
import { login } from '../store/rootSlice';
import { post } from '../http/http';

const LoginScreen = () => {
  const [mobilePhone, setMobilePhone] = useState(__DEV__ ? 'ddspladmin' : '');
  const [password, setPassword] = useState(__DEV__ ? 'ddspl2024' : '');
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const loginAction = async () => {
    try {
      const response = await post('/auth/auth/api/appRoomControlTeacherLoginApi', {
        mobilePhone,
        loginType: '1',
        password,
      });
      const data = response.data;
      // 假设 setUser 是一个全局状态管理的函数
      // setUser(data);
      console.log(data);
      dispatch(login(data));
      navigation.navigate('MainScreen');
    } catch (error) {
      Alert.alert('Error', error.message);
      if (error.message === 'token会话已过期,请重新登录') {
        // 清除用户数据
      }
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <ImageBackground source={ImageConstants.LOGIN_BCG} style={{ width: '100%', height: '100%' }}>
        <Image source={ImageConstants.INDEX_CLOUD} style={styles.image} />
        <Text style={styles.title}>HELLO</Text>
        <Text style={styles.subtitle}>欢迎来到国实实训平台{'\n'}管理端</Text>
        <View style={styles.form}>
          <TextInput
            style={styles.input}
            placeholder="请填写账号"
            value={mobilePhone}
            onChangeText={setMobilePhone}
          />
          <TextInput
            style={styles.input}
            placeholder="请输入密码"
            secureTextEntry
            value={password}
            onChangeText={setPassword}
          />
        </View>
        <View style={{ marginHorizontal: 30, borderRadius: 30, overflow: 'hidden' }}>
          <Button title="登录" onPress={loginAction} color="#52cca5" />
        </View>
      </ImageBackground>

    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  image: {
    width: '57%',
    position: 'absolute',
    top: 0,
    left: 0,
  },
  title: {
    fontWeight: 'bold',
    fontSize: 40,
    marginTop: 100,
    marginLeft: 30,
    color: 'white',
  },
  subtitle: {
    fontSize: 20,
    marginLeft: 30,
    width: '100%',
    color: 'white',
    marginTop: 15,
  },
  form: {
    padding: 30,
    borderRadius: 5,
    marginTop: 30,
    width: '100%',
  },
  input: {
    height: 40,
    borderColor: '#ccc',
    backgroundColor: '#fff',
    borderWidth: 1,
    marginBottom: 30,
    paddingLeft: 10,
    borderRadius: 5,
  },
});

export default LoginScreen;
